//login
var router =require('express').Router();
var crypto=require('crypto');
var captcha=require('../lib/captcha');
var User=require('../model/user');

module.exports = router;
router.get('/',(req, res)=>{
    if(req.session.user&&req.session.user._id)return res.redirect('/');
    var loginCache=req.session.loginCache;
    delete req.session.loginCache;
    res.render('login',{
        title:'Login',
        loginCache:loginCache,
        captcha:captcha(),
        flash:{
            error:req.flash('error').toString()
        },
        user:null
    });
});

router.post('/',(req,res,next)=>{
    var name=req.body.name,password=req.body.password,rememberme=req.body.rememberme;
    if(!(/^13\d{9}$/.test(name) || /^\w+@\w+\.\w+$/.test(name)) || 0==password.length){
        req.flash('error','用户名或密码输入错误');
        req.session.loginCache={name:name};
        return res.redirect('back');
    }
    password=crypto.createHash('md5').update(password).digest('hex');
    User.findOne({name:name,password:password},(err,user)=>{
        if(err)return next(err);
        if(!user){
            req.flash('error','用户名或密码输入错误');
            req.session.loginCache={name:name};
            return res.redirect('back');
        }
        req.session.user={
            _id:user._id.toString(),
            name:name
        };
        if(rememberme){
            res.cookie('username',name,{signed:true,maxAge:1000*3600*24*7/*7天*/,httpOnly:true, path:'/'});
        }else{
            res.clearCookie('username');
        }
        res.redirect('/');
    });
});